import {useState} from 'react'

import jdManagement from '../JdManagement.module.less'

import {updateTagsItem, deleteTagsItem } from '../../../api/index.js'

export default function TagManage({tags,onAddTag,onEditTag,onUpdateTag}){
    const [editId,setEditId] = useState('')
    const handleEdit=(value)=>{
        setEditId(value)
    }

    const handleSaveTitle = async (item)=>{
        setEditId('')
        // 调用修改接口
        await updateTagsItem(item)
        await onUpdateTag()
    }
    
    const deleteTagItem= async(id)=>{
        await deleteTagsItem(id)
        await onUpdateTag()
    }
    return(
        <div className={jdManagement.tagManage}>
            <div>
                标签管理
            </div>

            <ul className={jdManagement.tagMain}>
                {
                    tags.map(item=>{
                        return(
                           editId!==item.id && <li key={item.id} onClick={()=>handleEdit(item.id)}>{item.name}</li> ||
                           editId===item.id &&  <li key={item.id}>
                                                    <input type='text'  
                                                            defaultValue={item.name} 
                                                            onChange={(event)=>onEditTag(item.id,event.target.value)} 
                                                            value={item.name} 
                                                            />
                                                    <span onClick={()=>deleteTagItem(item.id)} style={{fontSize:'18px',marginLeft:'6px',color:'red'}}>X</span>
                                                    <span onClick={()=>handleSaveTitle(item)} style={{fontSize:'18px',marginLeft:'6px',color:'green'}}>√</span>
                                                </li> 
                        ) 
                    })
                }
            </ul>
            <div className={jdManagement.tagAddBtn} onClick={onAddTag}>+新增</div>
        </div>
    )

}